import {observable, action} from 'mobx';
import {Uploader} from '../models';
import { message } from 'antd';

class ImageStore {
    @observable filename:string = '';
    @observable file:File | null = null;
    @observable isUploading = false;
    @observable serverFile:any = null;

    @action setFilename(newFileName: string) {
        this.filename = newFileName
    }

    @action setFile(newFile: File) {
        this.file = newFile
    }

    @action upload() {
        this.isUploading = true;
        this.serverFile = null;
        return new Promise((resolve, reject) => {
            Uploader.add(this.file, this.filename)
                .then(serverFile => {
                    this.serverFile = serverFile
                    message.success('上传成功')
                    resolve(serverFile)
                })
                .catch(error => {
                    message.error('上传失败')
                    reject(error)
                })
                .finally(() => {
                    this.isUploading = false;
                })
            }
        )
    }

    @action reset() {
        this.isUploading = false;
        this.serverFile = null;
    }
}

export default new ImageStore()